package user

import (
	"ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/bean/request"
	"ZHONGYIHANGYAN/bean/response"
	commUtils "ZHONGYIHANGYAN/commUtils"
	"fmt"
)

// 获取用户列表
func (manage *UserManage) GetUserList(query *request.GetUserListQuery) (response.PageData, error) {
	pageData := response.PageData{}

	db := manage.DataBase.DB()
	tx := db.Model(&dbModel.User{})
	if query.Name != "" {
		tx = tx.Where("name LIKE ?", "%"+query.Name+"%")
	}
	if query.UserCode != "" {
		tx = tx.Where("user_code LIKE ?", "%"+query.UserCode+"%")
	}
	if query.RoleId != "" {
		tx = tx.Where("role_id = ?", query.RoleId)
	}

	// 获取总记录数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return pageData, err
	}
	if total == 0 {
		pageData.List = []interface{}{}
		return pageData, nil
	}

	// 分页查询
	currentPage := query.CurrentPage
	numPerPage := query.NumPerPage
	if currentPage <= 0 {
		currentPage = 1
	}
	if numPerPage <= 0 {
		numPerPage = 50
	}
	offset := (currentPage - 1) * numPerPage
	tx = tx.Order("user_code ASC").Limit(numPerPage).Offset(offset)

	var userList []response.GetUserListResponseInfo
	if err := tx.Find(&userList).Error; err != nil {
		return pageData, err
	}

	pageData.CurrentPage = currentPage
	pageData.NumPerPage = numPerPage
	pageData.TotalCount = int(total)
	pageData.TotalPages = (pageData.TotalCount + numPerPage - 1) / numPerPage
	pageData.List = userList

	return pageData, nil
}

// 添加或修改用户信息
func (manage *UserManage) AddOrUpdateUser(user *request.AddOrUpdateUserQuery) error {
	db := manage.DataBase.DB()

	isUpdate := user.Id != ""
	
	// 处理密码逻辑
	password := user.Password
	if !isUpdate && password == "" {
		// 新增用户且密码为空时，设置默认密码为用户code + "@bohui"
		password = user.UserCode + "@bohui"
	}
	pwd := commUtils.MakeMD5(password)


	if !isUpdate {
		userToCreate := dbModel.User{
			Id:       commUtils.GenUUID(),
			UserName: user.UserName,
			UserCode: user.UserCode,
			Password: pwd,
			RoleId: user.RoleId,
			DefaultUser: user.DefaultUser,
		}
		if err := db.Create(&userToCreate).Error; err != nil {
			return err
		}
	} else {
		idToUpdate := user.Id
		updateData := map[string]interface{}{
			"user_name": user.UserName,
			"user_code": user.UserCode,
			"password":  pwd,
			"role_id": user.RoleId,
			"default_user": user.DefaultUser,
		}

		result := db.Model(&dbModel.User{}).Where("id = ?", idToUpdate).Updates(updateData)
		if result.Error != nil {
			return result.Error
		}
		// 检查是否有记录被更新
		if result.RowsAffected == 0 {
			return fmt.Errorf("更新用户失败：ID 为 %d 的记录未找到", idToUpdate)
		}
	}
	return nil
}

// 删除直播资源
func (manage *UserManage) DeleteUser(userIds []string) error {
	if len(userIds) == 0 {
		return nil
	}

	db := manage.DataBase.DB()
	result := db.Where("id IN ?", userIds).Delete(&dbModel.User{})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("没有找到要删除的记录，ID列表可能无效或记录已被删除")
	}
	return nil
}
